﻿using System;
using DotNetNuke.Entities.Users;

namespace BigfootDNN.Mvc
{

    /// <summary>
    /// This is the base of the RouteHandler control. It is in charged of handling all MVC AJAX requests to the module.
    /// It is identical to the RouteUserControl except that it only ouputs to the response the result of the ajax call without 
    /// any initialization code. Sice it assumes that it is an ajax request, it also asumes that the page has already been 
    /// initialized and has the correct scripts etc. So only the content of the ActionResult is returned in the response
    /// </summary>
    public abstract class BaseRouteHandler : System.Web.IHttpHandler
    {

        /// <summary>
        /// This funciton must be overridden by the inheritor in order to Init the MVC application object
        /// </summary>
        public abstract DnnApp InitApp();

        public RouteInfo Route;
        public DnnApp App;
        
        public void ProcessRequest(System.Web.HttpContext context)
        {
            // Init the MVC app
            App = InitApp();
            try
            {
                // Get the current Route request
                var paramName = Params.QS.AjaxRoute(App.ModuleShortName);
                var routeData = App.Values.GetValue(paramName);
                
                // Route data must be present for an ajax request
                if (string.IsNullOrEmpty(routeData)) throw new ApplicationException("The Route data for this request is missing");

                // Create the Route from the url
                Route = App.DecodeUrlRoute(routeData);

                // Load the user if needed
                if (App.Request.IsAuthenticated)
                    Route.User = UserController.GetUserByName(Route.PortalId, App.Context.User.Identity.Name);

                // Execute the action
                var result = RouteHelper.ExecuteAction(Route);

                // Process the result
                ProcessResult(result);

            }
            catch (Exception ex)
            {
                App.HandleException(ex);
            }
        }

        private void ProcessResult(ActionResult result)
        {
            switch (result.Type)
            {
                case ActionResult.ActionTypeEnum.View:
                    result.Route.App.SetNoCache();
                    result.Route.App.RenderViewToResponse(result.Route.ViewPath, result.Data, "Route", result.Route);
                    break;
                case ActionResult.ActionTypeEnum.Literal:
                    result.Route.App.RenderLiteral(result.Data.ToString());
                    break;
                case ActionResult.ActionTypeEnum.Json:
                    result.Route.App.RenderJson(result.Data.ToString());
                    break;
            }
        }

        public bool IsReusable { get { return false; } }

    }

}
